import React from 'react';
import {App, Button, Card, Form, Input, InputNumber} from "antd";
import {Link, useLocation, useNavigate} from "react-router-dom";
import {GatewayRoute} from "type/entity/GatewayRoute";
import TextArea from "antd/es/input/TextArea";
import {filedArrayToStringObject, stringObjectToFiledArray} from "util/compare";
import {InputMultiple} from "common/form";
import RequestHandler from "http/RequestHandler";

const RouterFactoryUpdate = () => {
    const router = useLocation().state as GatewayRoute;
    const navigate = useNavigate();
    const { message } = App.useApp();
    const onFinish = async (value: GatewayRoute) => {
        value.metadata = filedArrayToStringObject(value.metadata as any);
        const res = await RequestHandler.post<number>("/manager/admin/route", value);
        if (res.success && res.data > 0) {
            message.success("更新路由信息成功");
            setTimeout(() => navigate("../"), 500);
        }else {
            message.info("修改失败");
        }
    };
    const metadata = stringObjectToFiledArray(router.metadata);

    return (
        <Card title={"更新信息"} extra={<Link to={".."} state={router}>路由列表</Link>}>
            <Form<GatewayRoute>
                name="dynamic_form_nest_item"
                onFinish={onFinish}
                labelCol={{span: 4}}
                wrapperCol={{span: 16}}
                autoComplete="off"
                initialValues={{...router, metadata}}
            >
                <Form.Item<GatewayRoute> name={"id"} label={"数据编号"} hidden>
                    <Input/>
                </Form.Item>
                <Form.Item<GatewayRoute> name={"routeId"} label={"路由ID"}>
                    <Input/>
                </Form.Item>
                <Form.Item<GatewayRoute> name={"uri"} label={"路由地址"}>
                    <Input/>
                </Form.Item>
                <Form.Item<GatewayRoute> name={"order"} label={"路由排序"}>
                   <InputNumber/>
                </Form.Item>
                <InputMultiple<GatewayRoute> name={"metadata"} label={"工厂元数据"}/>
                <Form.Item<GatewayRoute> name={"remark"} label={"备注信息"}>
                    <TextArea rows={3}/>
                </Form.Item>
                <Form.Item wrapperCol={{span: 6, offset: 4}}>
                    <Button type="primary" htmlType="submit">
                        提交修改
                    </Button>
                </Form.Item>
            </Form>
        </Card>
    );
};

export default RouterFactoryUpdate;